package com.zz.push.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;

public class JedisPoolUtil {

    private static final String HOST = "127.0.0.1";
    private static JedisPool pool;

    public static Jedis getJedis() {
        if (pool == null) {
            poolInit();
        }
        Jedis jedis = null;
        boolean borrowOrOprSuccess = true;
        try {
            jedis = pool.getResource();
        } catch (JedisConnectionException e) {
            borrowOrOprSuccess = false;
            if (jedis != null) {
                pool.returnBrokenResource(jedis);
            }

        } finally {
            if (borrowOrOprSuccess) {
                pool.returnResource(jedis);
            }
        }
        return pool.getResource();
    }

    private static synchronized void poolInit() {
        if (pool == null) {
            createJedisPool();
        }
    }

    private static void createJedisPool() {
        // 建立连接池配置参数
        JedisPoolConfig config = new JedisPoolConfig();
        // 设置最大连接数
        config.setMaxTotal(100);
        // 设置最大阻塞时间，记住是毫秒数milliseconds
        config.setMaxWaitMillis(1000);
        // 设置空间连接
        config.setMaxIdle(10);
        // 创建连接池
        pool = new JedisPool(config, HOST, 6379);
    }

    public static void returnRes(Jedis jedis) {
        jedis.close();
    }
}
